package com.caishi.lkx.common.fliter;

import cn.hutool.core.util.StrUtil;
import com.caishi.lkx.common.config.DiamondConfig;
import com.caishi.lkx.common.context.UserContext;
import com.caishi.lkx.common.util.IpAuthUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@Configuration
@Order(Integer.MIN_VALUE + 102)
public class IpFilter implements Filter {

    @Resource
    private DiamondConfig diamondConfig;

    @Resource
    private UserContext userContext;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        var device = userContext.currentTokenData().getDevice();
        if (device == null) {
            reject((HttpServletResponse) response);
            return;
        }
        if (!ipAuth(device.name())) {
            reject((HttpServletResponse) response);
            return;
        }
        filterChain.doFilter(servletRequest, response);
    }

    private void reject(HttpServletResponse response) throws IOException {
        response.setStatus(HttpStatus.FORBIDDEN.value());
        response.flushBuffer();
    }

    private boolean ipAuth(String device) {
        var ip = userContext.currentIp();
        var bmd = diamondConfig.getIpFilter().get(device);
        if (bmd != null && StrUtil.isNotBlank(bmd.get(0)) && IpAuthUtil.ipInIps(ip, bmd)) return true;
        var hmd = diamondConfig.getIpReject().get(device);
        return hmd == null || StrUtil.isBlank(hmd.get(0)) || !IpAuthUtil.ipInIps(ip, hmd);
    }
}
